#include "GamePlayLayer.h"
#include "StatusLayer.h"
#include "Global.h"
#include <SimpleAudioEngine.h>

USING_NS_CC;

bool GamePlayLayer::init()
{
	if(!Layer::init())
	{
		return false;
	}

	Size visibleSize = Director::getInstance()->getVisibleSize();
	auto cacher = SpriteFrameCache::getInstance();
	spriteRunner = Sprite::create("runner.png");
	spriteRunner->setPosition(Vec2(80, 85));

	Vector<SpriteFrame*> frames;

	for(int i = 0; i < 8; i++)
	{
		std::stringstream ss;
		ss << "runner" << i << ".png";
		frames.pushBack(cacher->getSpriteFrameByName(ss.str()));
	}

	auto anim = Animation::createWithSpriteFrames(frames, 0.1f);
	auto action = Animate::create(anim);
	auto anime = RepeatForever::create(action);

	spriteRunner->runAction(anime);
	this->addChild(spriteRunner);

	auto listener = EventListenerTouchOneByOne::create();
	listener->setSwallowTouches(true);
	listener->onTouchBegan = CC_CALLBACK_2(GamePlayLayer::onTouchBegan, this);
	getEventDispatcher()->addEventListenerWithFixedPriority(listener, 100);

	return true;
}

float GamePlayLayer::getEyeX()
{
	return spriteRunner->getPositionX() - Global::g_runnerStartX;
}

void GamePlayLayer::update(float dt)
{
	auto parent = getParent();
	auto statusLayer = (StatusLayer*)(parent->getChildByTag(TagOfLayer::STATUS_LAYER));
	statusLayer->updateMeter(spriteRunner->getPositionX() - Global::g_runnerStartX);
}

bool GamePlayLayer::onTouchBegan( Touch *pTouch, Event* event )
{
	spriteRunner->getPhysicsBody()->applyImpulse(Vect(0, 100), Point(0,0));
	auto audio = CocosDenshion::SimpleAudioEngine::getInstance(); 
	audio->playEffect("jump.mp3");
	return false;
}
